package gold.digger;

import gold.utils.InputUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC1438 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int longestSubarray(int[] nums, int limit) {
            int left = 0, right = 0, maxLen = 0;
            PriorityQueue<Integer> minQueue = new PriorityQueue<>();
            PriorityQueue<Integer> maxQueue = new PriorityQueue<>(Collections.reverseOrder());

            while (right < nums.length) {
                minQueue.offer(nums[right]);
                maxQueue.offer(nums[right]);
                while (maxQueue.peek() - minQueue.peek() > limit) {
                    maxQueue.remove(nums[left]);
                    minQueue.remove(nums[left++]);
                }
                maxLen = Math.max(maxLen, right++ - left + 1);
            }

            return maxLen;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[4,2,2,2,4,4,2,2]");
        System.out.println(solution.longestSubarray(arr, 0));
    }

    public static void main(String[] args) throws Exception {
        LC1438 an = new LC1438();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
